package com.ckcool.api.service.impl;

import cn.hutool.core.lang.Assert;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ckcool.api.entity.ProductSkuMapping;
import com.ckcool.api.service.LingXingInterfaceService;
import com.ckcool.api.service.ProductSkuMappingService;
import com.ckcool.api.util.RequestMethodKind;
import com.ckcool.api.util.RestUtilLingXing;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Administrator
 */
@Service
@Slf4j
public class LingXingInterfaceServiceImpl implements LingXingInterfaceService {

    private static final Logger logger = LoggerFactory.getLogger(LingXingInterfaceServiceImpl.class);

    @Resource
    private RestUtilLingXing restUtilLingXing;

    @Resource
    private ProductSkuMappingService mappingService;

    private static final String APPID = "";
    private static final String APP_SECRET = "==";

    private static final Map<String, Object> REQUEST_PARAMS = Map.of("appId", APPID, "appSecret", APP_SECRET);

    private static final String TOKEN_URL = "https://openapi.lingxing.com/api/auth-server/oauth/access-token";
    private static final String PRODUCT_INFO_URL = "https://openapi.lingxing.com" +
            "/erp/sc/routing/data/local_inventory/productInfo";

    private static final String PRODUCT_SET_URL = "https://openapi.lingxing.com" +
            "/erp/sc/routing/storage/product/set";

    private static final String PRODUCT_LABEL_URL = "https://openapi.lingxing.com" +
            "/label/operation/v1/label/product/mark";

    private static final int PRODUCT_HEAD = 10315959;


    @Override
    public void syncProductInfo(String sku) throws Exception {
        //获取token
        String token = getToken();

        if (sku == null) {
            return;
        }
        //定义查询参数
        JSONObject productInfoResult = getQueryObject(sku, token);
        if (!"0".equals(productInfoResult.get("code").toString())) {
            Assert.isTrue(false, "查询产品详情失败，原因：" + productInfoResult.get("msg").toString());
        }
        JSONObject result = productInfoResult.getJSONObject("data");
        try {
            //handleProductInfoResult(result);
            System.out.println(result);
        } catch (Exception e) {
            log.info("产品入库失败{}", e.getMessage());
        }
    }

    private JSONObject getQueryObject(String sku, String token) throws Exception {
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("sku", sku);
        //定义URL参数
        Map<String, Object> requestParams = new HashMap<>();
        requestParams.put("access_token", token);
        requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
        requestParams.put("timestamp", System.currentTimeMillis() / 1000);
        //产品详情
        return (JSONObject) restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                requestParams, LingXingInterfaceServiceImpl.PRODUCT_INFO_URL,
                null, requestBody);
    }

    @Override
    public void addProductSku(String oldSku, String newSku, String addSku) throws Exception {
        // 获取token
        String token = getToken();
        if (oldSku == null || newSku == null || addSku == null) {
            return;
        }
        JSONObject result = null;
        try {
            result = productInfo(oldSku, token);
            /*if (result == null) {
                // 处理 result 为 null 的情况
                logger.warn("旧 SKU={} 的产品信息返回了 null", oldSku);
            }*/
        } catch (Exception e) {
            logger.warn("获取旧 SKU={} 的产品信息时发生异常: {}", oldSku, e.getMessage());
        }

        JSONObject addSkuRes = null;
        try {
            addSkuRes = productInfo(addSku, token);
        } catch (Exception e) {
            System.err.println("addSku: " + addSku + "不存在" + e.getMessage());
        }

        if (addSkuRes == null || addSkuRes.isEmpty()) {
            try {
                addProduct(addSku, result, token, null);
                logger.info("成功添加SKU : oldSku={},addSku={}",
                        oldSku, addSku);
            } catch (Exception e) {
                logger.error("添加失败商品不存在 : oldSku={},addSku={}", oldSku, addSku);
            }
        } else {
            System.out.println("addSku: 裸品" + addSku + "已存在，忽略" );
            JSONObject newSkuRes = null;
            try {
                newSkuRes = productInfo(newSku, token);
            } catch (Exception e) {
                System.err.println("addSku: " + newSku + "不存在" + e.getMessage());
            }

            if (newSkuRes != null && !newSkuRes.isEmpty()) {
                System.out.println("newSku: 成品" + newSku + "已存在，忽略"  );
            } else {
                try {
                    addProduct(newSku, result, token, addSkuRes);
                    logger.info("成功添加SKU : oldSku={},newSku={},addSku={}",
                            oldSku, newSku, addSku);
                } catch (Exception e) {
                    logger.info("添加失败 : oldSku={},newSku={},addSku={}",
                            oldSku, newSku, addSku);
                }
            }
        }
    }

    @Override
    public void processProductSkuMappings() throws Exception {
        List<ProductSkuMapping> skuMappings = mappingService.list();
        int i = 1;
        for (ProductSkuMapping mapping : skuMappings) {
            addProductSku(mapping.getOldSku(), mapping.getNewSku(), mapping.getAddSku());
            System.out.println("第 " + i + " 条 --" + mapping.getOldSku() + " "+mapping.getNewSku() + " "+mapping.getAddSku());
            System.out.println(" ");
            i++;
        }
    }

    private JSONObject productInfo(String oldSku, String token) throws Exception {
        // 定义查询参数
        JSONObject productInfoResult = getQueryObject(oldSku, token);
        if (productInfoResult == null) {
            // 处理 productInfoResult 为 null 的情况
            throw new Exception("查询结果为空");
        }
        if (!"0".equals(productInfoResult.get("code").toString())) {
            //Assert.isTrue(false, "查询产品详情失败，原因：" + productInfoResult.get("msg").toString());
            System.out.println(productInfoResult.get("msg").toString());
            return null;
        }
        return productInfoResult.getJSONObject("data");
    }

    private void addProduct(String newSku, JSONObject result, String token, JSONObject addSkuRes) throws Exception {
        Map<String, Object> updateRequestBody = new HashMap<>();
        updateRequestBody.put("sku", newSku);
        String productName = result.getString("product_name");
        if (productName != null && !productName.trim().isEmpty()) {
            updateRequestBody.put("product_name", productName);
        }

        JSONArray pictureList = result.getJSONArray("picture_list");
        if (pictureList != null && !pictureList.isEmpty()) {
            updateRequestBody.put("picture_list", pictureList);
        }

        String unit = result.getString("unit");
        if (unit != null && !unit.trim().isEmpty()) {
            updateRequestBody.put("unit", unit);
        }

        Integer categoryId = result.getInteger("cid");
        if (categoryId != null) {
            updateRequestBody.put("category_id", categoryId);
        }

        String model = result.getString("model");
        if (model != null && !model.trim().isEmpty()) {
            updateRequestBody.put("model", model);
        }

        Integer brandId = result.getInteger("bid");
        if (brandId != null) {
            updateRequestBody.put("brand_id", brandId);
        }

        Integer status = result.getInteger("status");
        if (status != null) {
            updateRequestBody.put("status", status);
        }

        String description = result.getString("description");
        if (description != null && !description.trim().isEmpty()) {
            updateRequestBody.put("description", description);
        }

        if (addSkuRes != null) {
            JSONArray groupList = new JSONArray();
            JSONObject groupItem = new JSONObject();
            String sku = addSkuRes.getString("sku");
            groupItem.put("sku", sku);
            groupItem.put("quantity", 1);
            groupList.add(groupItem);
            updateRequestBody.put("group_list", groupList);
        }

        Integer productDeveloperUid = result.getInteger("product_developer_uid");
        if (productDeveloperUid != null) {
            updateRequestBody.put("product_developer_uid", productDeveloperUid);
        }
        updateRequestBody.put("product_creator_uid", PRODUCT_HEAD);

        String productDeveloper = result.getString("product_developer");
        if (productDeveloper != null && !productDeveloper.trim().isEmpty()) {
            updateRequestBody.put("product_developer", productDeveloper);
        }

        JSONArray permissionUserInfoArray = result.getJSONArray("permission_user_info");
        if (permissionUserInfoArray != null && !permissionUserInfoArray.isEmpty()) {
            JSONArray productDutyUids = new JSONArray();
            for (int i = 0; i < permissionUserInfoArray.size(); i++) {
                JSONObject userInfo = permissionUserInfoArray.getJSONObject(i);
                Integer permissionUid = userInfo.getInteger("permission_uid");
                if (permissionUid != null) {
                    productDutyUids.add(permissionUid);
                }
            }
            updateRequestBody.put("product_duty_uids", productDutyUids);
        }

        updateRequestBody.put("is_append_product_duty", 0);

        String purchaseRemark = result.getString("purchase_remark");
        if (purchaseRemark != null && !purchaseRemark.trim().isEmpty()) {
            updateRequestBody.put("purchase_remark", purchaseRemark);
        }

        String cgPrice = result.getString("cg_price");
        if (cgPrice != null && !cgPrice.trim().isEmpty()) {
            updateRequestBody.put("cg_price", cgPrice);
        }

        Integer cgDelivery = result.getInteger("cg_delivery");
        if (cgDelivery != null) {
            updateRequestBody.put("cg_delivery", cgDelivery);
        }

        String cgProductMaterial = result.getString("cg_product_material");
        if (cgProductMaterial != null && !cgProductMaterial.trim().isEmpty()) {
            updateRequestBody.put("cg_product_material", cgProductMaterial);
        }

        String cgProductLength = result.getString("cg_product_length");
        if (cgProductLength != null && !cgProductLength.trim().isEmpty()) {
            updateRequestBody.put("cg_product_length", cgProductLength);
        }

        String cgProductWidth = result.getString("cg_product_width");
        if (cgProductWidth != null && !cgProductWidth.trim().isEmpty()) {
            updateRequestBody.put("cg_product_width", cgProductWidth);
        }

        String cgProductHeight = result.getString("cg_product_height");
        if (cgProductHeight != null && !cgProductHeight.trim().isEmpty()) {
            updateRequestBody.put("cg_product_height", cgProductHeight);
        }

        String cgProductNetWeight = result.getString("cg_product_net_weight");
        if (cgProductNetWeight != null && !cgProductNetWeight.trim().isEmpty()) {
            updateRequestBody.put("cg_product_net_weight", cgProductNetWeight);
        }

        String cgProductGrossWeight = result.getString("cg_product_gross_weight");
        if (cgProductGrossWeight != null && !cgProductGrossWeight.trim().isEmpty()) {
            updateRequestBody.put("cg_product_gross_weight", cgProductGrossWeight);
        }

        String cgPackageLength = result.getString("cg_package_length");
        if (cgPackageLength != null && !cgPackageLength.trim().isEmpty()) {
            updateRequestBody.put("cg_package_length", cgPackageLength);
        }

        String cgPackageWidth = result.getString("cg_package_width");
        if (cgPackageWidth != null && !cgPackageWidth.trim().isEmpty()) {
            updateRequestBody.put("cg_package_width", cgPackageWidth);
        }

        String cgPackageHeight = result.getString("cg_package_height");
        if (cgPackageHeight != null && !cgPackageHeight.trim().isEmpty()) {
            updateRequestBody.put("cg_package_height", cgPackageHeight);
        }

        String cgBoxLength = result.getString("cg_box_length");
        if (cgBoxLength != null && !cgBoxLength.trim().isEmpty()) {
            updateRequestBody.put("cg_box_length", cgBoxLength);
        }

        String cgBoxWidth = result.getString("cg_box_width");
        if (cgBoxWidth != null && !cgBoxWidth.trim().isEmpty()) {
            updateRequestBody.put("cg_box_width", cgBoxWidth);
        }

        String cgBoxHeight = result.getString("cg_box_height");
        if (cgBoxHeight != null && !cgBoxHeight.trim().isEmpty()) {
            updateRequestBody.put("cg_box_height", cgBoxHeight);
        }

        String cgBoxWeight = result.getString("cg_box_weight");
        if (cgBoxWeight != null && !cgBoxWeight.trim().isEmpty()) {
            updateRequestBody.put("cg_box_weight", cgBoxWeight);
        }

        Integer cgBoxPcs = result.getInteger("cg_box_pcs");
        if (cgBoxPcs != null) {
            updateRequestBody.put("cg_box_pcs", cgBoxPcs);
        }

        String bgCustomsExportName = result.getString("bg_customs_export_name");
        if (bgCustomsExportName != null && !bgCustomsExportName.trim().isEmpty()) {
            updateRequestBody.put("bg_customs_export_name", bgCustomsExportName);
        }

        String bgExportHsCode = result.getString("bg_export_hs_code");
        if (bgExportHsCode != null && !bgExportHsCode.trim().isEmpty()) {
            updateRequestBody.put("bg_export_hs_code", bgExportHsCode);
        }

        String bgCustomsImportName = result.getString("bg_customs_import_name");
        if (bgCustomsImportName != null && !bgCustomsImportName.trim().isEmpty()) {
            updateRequestBody.put("bg_customs_import_name", bgCustomsImportName);
        }

        String currency = result.getString("currency");
        if (currency != null && !currency.trim().isEmpty()) {
            updateRequestBody.put("currency", currency);
        }

        String bgCustomsImportPrice = result.getString("bg_customs_import_price");
        if (bgCustomsImportPrice != null && !bgCustomsImportPrice.trim().isEmpty()) {
            updateRequestBody.put("bg_customs_import_price", bgCustomsImportPrice);
        }

        JSONObject qcStandard = result.getJSONObject("qc_standard");
        if (qcStandard != null && !qcStandard.isEmpty()) {
            updateRequestBody.put("qc_standard", qcStandard);
        }

        JSONArray productLogisticsArray = result.getJSONArray("product_logistics_relation");
        if (productLogisticsArray != null && !productLogisticsArray.isEmpty()) {
            JSONObject combinedObject = new JSONObject();
            for (int i = 0; i < productLogisticsArray.size(); i++) {
                JSONObject jsonObject = productLogisticsArray.getJSONObject(i);
                for (String key : jsonObject.keySet()) {
                    combinedObject.put(key, jsonObject.get(key));
                }
            }
            updateRequestBody.put("product_logistics_list", combinedObject);
        }
        JSONArray supplierQuoteArray = result.getJSONArray("supplier_quote");
        JSONArray requestSupplierQuoteArray = new JSONArray();
        if (supplierQuoteArray != null) {
            for (int i = 0; i < supplierQuoteArray.size(); i++) {
                JSONObject supplierQuote = supplierQuoteArray.getJSONObject(i);
                JSONObject requestSupplierQuote = new JSONObject();
                // 处理字段
                // 获取供应商 ID
                Integer supplierId = supplierQuote.getInteger("supplier_id");
                if (supplierId != null) {
                    requestSupplierQuote.put("erp_supplier_id", supplierId);
                }
                requestSupplierQuote.put("supplier_product_url", supplierQuote.containsKey("supplier_product_url") ? supplierQuote.getJSONArray("supplier_product_url") : null);
                requestSupplierQuote.put("quote_remark", supplierQuote.getString("quote_remark"));
                requestSupplierQuote.put("is_primary", supplierQuote.getInteger("is_primary"));
                // 处理 quotes 部分
                JSONArray quotesArray = supplierQuote.containsKey("quotes") ? supplierQuote.getJSONArray("quotes") : null;
                JSONArray requestQuotesArray = new JSONArray();
                if (quotesArray != null) {
                    for (int j = 0; j < quotesArray.size(); j++) {
                        JSONObject quote = quotesArray.getJSONObject(j);
                        JSONObject requestQuote = new JSONObject();

                        requestQuote.put("currency", quote.getString("currency"));
                        requestQuote.put("is_tax", quote.getInteger("is_tax"));
                        requestQuote.put("tax_rate", quote.getString("tax_rate"));

                        // 处理 step_prices 部分
                        JSONArray stepPricesArray = quote.containsKey("step_prices") ? quote.getJSONArray("step_prices") : null;
                        JSONArray requestStepPricesArray = new JSONArray();
                        if (stepPricesArray != null) {
                            for (int k = 0; k < stepPricesArray.size(); k++) {
                                JSONObject stepPrice = stepPricesArray.getJSONObject(k);
                                JSONObject requestStepPrice = new JSONObject();

                                requestStepPrice.put("moq", stepPrice.getInteger("moq"));
                                requestStepPrice.put("price_with_tax", stepPrice.getString("price_with_tax")); // 按字符串处理

                                requestStepPricesArray.add(requestStepPrice);
                            }
                        }
                        requestQuote.put("step_prices", requestStepPricesArray);
                        requestQuotesArray.add(requestQuote);
                    }
                }
                requestSupplierQuote.put("quotes", requestQuotesArray);
                requestSupplierQuoteArray.add(requestSupplierQuote);
            }
        }
        updateRequestBody.put("supplier_quote", requestSupplierQuoteArray);

        JSONArray specialAttr = result.getJSONArray("special_attr");
        if (specialAttr != null && !specialAttr.isEmpty()) {
            updateRequestBody.put("special_attr", specialAttr);
        }

        JSONObject declaration = result.getJSONObject("declaration");
        if (declaration != null && !declaration.isEmpty()) {
            updateRequestBody.put("declaration", declaration);
        }

        JSONObject clearance = result.getJSONObject("clearance");
        if (clearance != null && !clearance.isEmpty()) {
            updateRequestBody.put("clearance", clearance);
        }


        // 发送更新请求
        Map<String, Object> updateParams = new HashMap<>();
        updateParams.put("access_token", token);
        updateParams.put("app_key", REQUEST_PARAMS.get("appId"));
        updateParams.put("timestamp", System.currentTimeMillis() / 1000);

        Object updateResult = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                updateParams, PRODUCT_SET_URL,
                null, updateRequestBody);

        JSONObject updateResultObj = (JSONObject) updateResult;
        System.out.println(updateResultObj);
        if (!"0".equals(updateResultObj.get("code").toString())) {
            Assert.isTrue(false, "更新产品信息失败，原因：" + updateResultObj.get("msg").toString());
        }

        JSONArray globalTags = result.getJSONArray("global_tags");
        if (globalTags != null && !globalTags.isEmpty()) {
            // 发送产品标签请求
            Map<String, Object> labelParams = new HashMap<>();
            labelParams.put("access_token", token);
            labelParams.put("app_key", REQUEST_PARAMS.get("appId"));
            labelParams.put("timestamp", System.currentTimeMillis() / 1000);

            // 定义查询参数
            Map<String, Object> requestLabelBody = new HashMap<>();
            requestLabelBody.put("type", 1);
            JSONArray detailListArray = new JSONArray();
            // 创建一个新的 detail 对象
            JSONObject detail = new JSONObject();
            detail.put("sku", newSku); // SKU 可能需要从其他地方获取或设置一个默认值
            JSONArray labelListArray = new JSONArray();
            // 提取每个标签的 tag_name 并添加到 label_list
            for (int i = 0; i < globalTags.size(); i++) {
                JSONObject tag = globalTags.getJSONObject(i);
                String tagName = tag.getString("tag_name");
                if (tagName != null) {
                    labelListArray.add(tagName);
                }
            }
            detail.put("label_list", labelListArray);

            // 将 detail 添加到 detail_list 中
            detailListArray.add(detail);
            requestLabelBody.put("detail_list", detailListArray);
            // 产品详情
            Object productLabelResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                    labelParams, PRODUCT_LABEL_URL,
                    null, requestLabelBody);
            JSONObject productLabelResult = (JSONObject) productLabelResultObj;

            if (!"0".equals(productLabelResult.get("code").toString())) {
                Assert.isTrue(false, "查询产品详情失败，原因：" + productLabelResult.get("msg").toString());
            }
        }
    }

    //    8f8ad28f-d084-453b-a888-7dc3ca4655bb

    /**
     * getToken
     *
     * @return token
     * @throws Exception 异常
     */
    @Override
    public String getToken() throws Exception {
        Object lingXingRequest = restUtilLingXing.lingXingRequest("1", RequestMethodKind.Post.getValue(), REQUEST_PARAMS,
                TOKEN_URL, null, null);
        JSONObject jsonObject = (JSONObject) lingXingRequest;
        if (!"200".equals(jsonObject.get("code"))) {
            Assert.isTrue(false, "获取AccessToken失败，错误信息：" + jsonObject.get("msg"));
        }
        //取得access-token
        return ((JSONObject) jsonObject.get("data")).get("access_token").toString();
    }
}
